<?php

if (isset($_REQUEST['php_session_id'])) session_id($_REQUEST['php_session_id']);

session_start();

// Find out where we're installed
$app_root = realpath(dirname(dirname(dirname(__FILE__))));

// Add the include path 
ini_set('include_path', $app_root . '/admin/includes:' . ini_get('include_path'));

// Force UTC
date_default_timezone_set('UTC');

// Get the app config
require $app_root . '/config.php';

// DB connect
try {
	$db = Zend_Db::factory($config['db_factory'], array(
	    'host'     => $config['db_host'],
	    'username' => $config['db_user'],
	    'password' => $config['db_pass'],
	    'dbname'   => $config['db_database']
	));
    $db->getConnection();
	$db->query("SET NAMES 'utf8'");
	if (isset($config['zend_profiler']) and $config['zend_profiler']) {
		$db->getProfiler()->setEnabled(true);
	}
} catch (Zend_Db_Adapter_Exception $e) {
	// perhaps a failed login credential, or perhaps the RDBMS is not running
	echo $e->getMessage();
	exit;
} catch (Zend_Exception $e) {
	// perhaps factory() failed to load the specified Adapter class
	echo $e->getMessage();
	exit;
}

/*
 * Identify which site we're on, and redirect to primary domain
 * if we're on an alias.
 *
 */
if (isset($_SESSION['site']) and is_dir($app_root . $_SESSION['site']['home_dir'])) {
	$site = $_SESSION['site'];
} else {
	$site = $db->fetchRow("SELECT id, domain_name, home_dir FROM cms_sites WHERE ? REGEXP domain_regex", $_SERVER['SERVER_NAME']);
	if ($site) $_SESSION['site'] = $site;
}
if (!$site['id']) {
	echo "Invalid domain.\n";
	exit;
} elseif($_SERVER['SERVER_NAME'] != $site['domain_name']) {
	header("Location: " . (isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . $site['domain_name'] . $_SERVER['REQUEST_URI']);
	exit;
}

// Smarty
require "Smarty/Smarty.class.php";
$smarty = new Smarty;
$smarty->compile_dir = $app_root . '/admin/templates_c';
if ($config['smarty_use_sub_dirs']) $smarty->use_sub_dirs = true;
$smarty->assign('cms_name', $config['cms_name']);
$smarty->assign('cms_domain', $config['cms_domain']);
$smarty->assign('cms_version', file_get_contents(dirname(dirname(__FILE__)) . '/version'));
$smarty->assign('site', $site);
require 'modifier.date.php';

/*
 * Split the path up into its component parts.
 *
 */
$path = explode('/', rtrim($_GET['path'], '/'));
$smarty->assign('path', $path);

/*
 * Get the environment from the database.  The table holds keys and
 * values, but we want to split the keys up on : and make a multilevel
 * array, so for instance, if the key is google:adwords:id, we would
 * have $env['google']['adwords']['id']
 *
 */
$env = array();
$result = $db->fetchAll("SELECT `key`, `value` FROM cms_environment WHERE site_id=? ORDER BY `key`", $site['id']);
foreach($result as $row) {
	$key = explode(':', $row['key']);
    $nodeRef = &$env;
    for($i=0;$i<sizeof($key);$i++) {
        if (!isset($nodeRef[$key[$i]])) {
            if ($i == sizeof($key)-1) $nodeRef[$key[$i]] = $row['value'];
            else $nodeRef[$key[$i]] = array();
        }
        $nodeRef = &$nodeRef[$key[$i]];
    }
}
$smarty->assign('env', $env);

/*
 * Setup logging.
 *
 */
$logger = new Zend_Log();
$logger->addWriter(new Zend_Log_Writer_Null);
if (isset($env['log'])) {
	if (isset($env['log']['file']) and $env['log']['file']) {
		$writer_file = new Zend_Log_Writer_Stream($app_root . $site['home_dir'] . '/' . ($env['log']['file']['filename'] ? $env['log']['file']['filename'] : $site['domain_name'] . '.log'));
		$writer_file->addFilter(new Zend_Log_Filter_priority((int)(isset($env['log']['file']['level']) ? $env['log']['file']['level'] : 0)));
		$logger->addWriter($writer_file);
	}
	if (isset($env['log']['firebug']) and $env['log']['firebug']) {
		$writer_firebug = new Zend_Log_Writer_Firebug();
		$writer_firebug->addFilter(new Zend_Log_Filter_priority((int)(isset($env['log']['firebug']['level']) ? $env['log']['firebug']['level'] : 7)));
		$logger->addWriter($writer_firebug); 
		$request = new Zend_Controller_Request_Http();
		$response = new Zend_Controller_Response_Http();
		$channel = Zend_Wildfire_Channel_HttpHeaders::getInstance();
		$channel->setRequest($request);
		$channel->setResponse($response);
		ob_start();
	}
}

/*
 * Ensure that we have a custom users table for this site
 *
 */
$tables = $db->fetchCol("SHOW TABLES");
if (!in_array("cms_users_custom_{$site['id']}", $tables)) {
	$db->query("CREATE TABLE cms_users_custom_{$site['id']} LIKE cms_users_custom_skel");
}

/*
 * Intercept a login attempt here, and process it.  This way, the actual login pages,
 * front end or back, already have the results available to them.  On success set 
 * $_SESSION['login'].  On success or failure, set $login_succeeded.
 * 
 */
require 'Password.class.php';
if (isset($_POST['login'])) {
	if (isset($_SESSION['login'])) {
		unset($_SESSION['login']);
	}
	$login_succeeded = false;
	if (isset($_POST['login']['username'])) {
		$user = $db->fetchRow("SELECT * FROM cms_users WHERE site_id=? AND username=?", array($site['id'], $_POST['login']['username']));
	} elseif(isset($_POST['login']['email'])) {
		$user = $db->fetchRow("SELECT * FROM cms_users WHERE site_id=? AND email=?", array($site['id'], $_POST['login']['email']));
	} elseif(isset($_POST['login']['username_or_email'])) {
		$user = $db->fetchRow("SELECT * FROM cms_users WHERE site_id=? AND (username=? OR email=?)", array($site['id'], $_POST['login']['username_or_email'], $_POST['login']['username_or_email']));
	}
	if ($user and Password::auth($_POST['login']['password'], $user['password'])) {
		session_regenerate_id();
		$user['custom_fields'] = $db->fetchRow("SELECT * FROM cms_users_custom_{$site['id']} WHERE user_id=?", $user['id']);
		$user['access_rights'] = unserialize($user['access_rights']);
		$_SESSION['login'] = array('user' => $user, 'timestamp' => time());
		$login_succeeded = true;
		unset($user);
	}
}

/*
 * Check login, and if it's valid, then set the timestamp.  If not,
 * then nuke the login.
 *
 */
if ($path[0] != 'timeout') {
	if (isset($_SESSION['login']) and time() - $_SESSION['login']['timestamp'] < (isset($env['timeout']) ? $env['timeout'] : 1800)) {
		$_SESSION['login']['timestamp'] = time();
	} else {
		unset($_SESSION['login']);
	}
}

/*
 * Set the session in in smarty as we'll need it for file uploads.
 *
 */
$smarty->assign('session_id', session_id());

/*
 * Assorted generic functions that should really already be
 * in PHP.
 *
 */
require 'functions.php';

/*
 * Class autoloader - currently just configured for Zend
 * style.  Replaces _ with / and adds .php
 *
 */
function __autoload($class) {
	$class = str_replace('_', '/', $class) . '.php';
	require_once($class);
}